package cn.epsilon3.configuration;

import cn.epsilon3.configBean.InitializingAsyncScheduledConfig;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @description 线程池配置
 *
 * @author: epsilon3
 * @date: 2023/9/5 13:37
 */
@Configuration
public class ThreadPoolConfiguration {

    /**
     * yaml配置映射实体
     */
    @Resource
    private InitializingAsyncScheduledConfig initializingAsyncScheduledConfig;

    /**
     * 计划执行bean
     *
     * @return ScheduledExecutorService
     */
    @Bean("e3ScheduledExecutorService")
    public ScheduledExecutorService scheduledExecutorService() {
        return new ScheduledThreadPoolExecutor(initializingAsyncScheduledConfig.getPoolCoreSize(),
                new BasicThreadFactory.Builder().namingPattern("e3-schedule-%d").daemon(true).build(),
                new ThreadPoolExecutor.CallerRunsPolicy()){
            @Override
            protected void afterExecute(Runnable r, Throwable t) {
                super.afterExecute(r, t);
            }
        };
    }
}
